using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace SeguradoraIA.Framework.Log
{
    public class ObjectStructure
    {
        private static readonly Dictionary<Type, ObjectStructure> objectStructureList = new Dictionary<Type, ObjectStructure>();

        internal static ObjectStructure GetObjectStructure(object obj)
        {
            Type tipo = obj.GetType();

            ObjectStructure objectStructure = null;

            if (objectStructureList.ContainsKey(tipo))
            {
                objectStructure = objectStructureList[tipo];
            }
            else
            {
                objectStructure = new ObjectStructure();

                objectStructure.Tipo = tipo;

                foreach (PropertyInfo propriedade in tipo.GetProperties())
                {
                    objectStructure.Propriedades.Add(propriedade);
                }

                foreach (FieldInfo campo in tipo.GetFields())
                {
                    objectStructure.Campos.Add(campo);
                }
                objectStructureList.Add(objectStructure.Tipo, objectStructure);
            }

            objectStructure.Value = obj;

            return objectStructure;
        }




        public List<PropertyInfo> Propriedades = new List<PropertyInfo>();
        public List<FieldInfo> Campos = new List<FieldInfo>();
        public Type Tipo;

        public object Value{get; set;}

        public override string ToString()
        {
            string retorno = string.Empty;
            StringBuilder sb = new StringBuilder();

            
            foreach (PropertyInfo property in Propriedades)
            {
                sb.Append(property.GetValue(Value, null));
                sb.Append(",");
            }
            foreach (FieldInfo field in Campos)
            {
                sb.Append(field.GetValue(Value));
                sb.Append(",");
            }

            string conteudo = sb.ToString();
            conteudo = conteudo.Trim(',');
            if (conteudo == string.Empty)
            {
                retorno = Value.ToString();
            }
            else
            {
                retorno = Tipo.Name + "[" + conteudo + "]";
            }

            return retorno;
        }

    }
}